package service

import (
	baseAuth "gitee.com/zaiqiang231/go-base-app/base_app/auth"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model/req"
	"gitee.com/zaiqiang231/lovesport-user-service/app/store"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type ServiceUser struct{}

var ServiceUserInstance = new(ServiceUser)

func (service *ServiceUser) SetUserAuthority(id uint, authorityId uint) (err error) {
	store.GetDataStore().User().Execute(func(db *gorm.DB) {
		assignErr := db.Where("sys_user_id = ? AND sys_authority_authority_id = ?", id, authorityId).First(&model.SysUserAuthority{}).Error
		if errors.Is(assignErr, gorm.ErrRecordNotFound) {
			err = errors.New("该用户无此角色")
		}
		err = db.Where("id = ?", id).First(&model.User{}).Update("authority_id", authorityId).Error
	})
	return err
}

func (service *ServiceUser) SetUserAuthorities(id uint, authorityIds []uint) (err error) {
	store.GetDataStore().User().Execute(func(db *gorm.DB) {
		var targetAuthority []model.SysAuthority
		err = db.Where("authority_id in (?)", authorityIds).Find(&targetAuthority).Error
		if err != nil {
			return
		}
		var user model.User
		err = db.Where("id = ?", id).First(&user).Error
		err = db.Model(&user).Association("Authorities").Replace(targetAuthority)
	})
	return err
}

func (service *ServiceUser) SetUserPassword(id uint, password string) (err error) {
	store.GetDataStore().User().Execute(func(db *gorm.DB) {
		passwordEncrypt, errtemp := baseAuth.Encrypt(password)
		if errtemp != nil {
			err = errtemp
			return
		}
		err = db.Model(&model.User{}).Where("id = ?", id).Update("password", passwordEncrypt).Error
		if err != nil {
			return
		}
	})
	return err
}

func (service *ServiceUser) GetUserInfoList(info req.PageInfo) (list interface{}, total int64, err error) {
	store.GetDataStore().User().Execute(func(db *gorm.DB) {
		limit := info.PageSize
		offset := info.PageSize * (info.Page - 1)
		var userList []model.User
		err = db.Model(&model.User{}).Count(&total).Error
		if err != nil {
			return
		}
		err = db.Model(&model.User{}).Offset(offset).Limit(limit).Preload("Authorities").Preload("Authority").Find(&userList).Error
		if err != nil {
			return
		}
		list = userList
	})
	return
}

func (service *ServiceUser) Update(user map[string]interface{}) (err error) {
	store.GetDataStore().User().Execute(func(db *gorm.DB) {
		var old model.User
		if errors.Is(db.Where("id = ?", user["id"]).First(&old).Error, gorm.ErrRecordNotFound) {
			err = errors.New("原记录不存在")
		} else {
			if !errors.Is(db.Where("id <> ? AND name = ?", user["id"], user["name"]).First(&model.User{}).Error, gorm.ErrRecordNotFound) {
				err = errors.New("存在相同name修改失败")
			}
		}
		if err != nil {
			return
		}
		err = db.Model(&old).Updates(user).Error
	})
	return err
}
